<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="优惠券码" prop="couponCode">
        <el-input
          v-model="queryParams.couponCode"
          placeholder="请输入优惠券码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="优惠券名称" prop="couponName">
        <el-input
          v-model="queryParams.couponName"
          placeholder="请输入优惠券名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="优惠券类型" prop="couponType">
        <el-select v-model="queryParams.couponType" placeholder="请选择优惠券类型" clearable>
          <el-option
            v-for="dict in dict.type.ec_coupon_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="过期时间" prop="expireTime">
        <el-date-picker clearable
          v-model="queryParams.expireTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择过期时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['fun:conponList:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['fun:conponList:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['fun:conponList:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['fun:conponList:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="conponListList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="优惠券码" align="center" prop="couponCode" />
      <el-table-column label="优惠券名称" align="center" prop="couponName" />
      <el-table-column label="优惠券类型" align="center" prop="couponType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ec_coupon_type" :value="scope.row.couponType"/>
        </template>
      </el-table-column>
      <el-table-column label="优惠金额" align="center" prop="couponAmount" />
      <el-table-column label="折扣率" align="center" prop="discountRate" />
      <el-table-column label="最低消费金额" align="center" prop="minAmount" />
      <el-table-column label="最高优惠金额" align="center" prop="maxAmount" />
      <el-table-column label="过期时间" align="center" prop="expireTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.expireTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="来源渠道" align="center" prop="source" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['fun:conponList:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['fun:conponList:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改优惠券列表对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <!-- 第一行：优惠券码、优惠券名称、优惠券类型 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="优惠券码" prop="couponCode">
              <el-input v-model="form.couponCode" placeholder="请输入优惠券码" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="优惠券名称" prop="couponName">
              <el-input v-model="form.couponName" placeholder="请输入优惠券名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="优惠券类型" prop="couponType">
              <el-select v-model="form.couponType" placeholder="请选择优惠券类型" style="width: 100%">
                <el-option
                  v-for="dict in dict.type.ec_coupon_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 第二行：优惠金额、折扣率、最低消费金额 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="优惠金额" prop="couponAmount">
              <el-input v-model="form.couponAmount" placeholder="请输入优惠金额" type="number" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="折扣率" prop="discountRate">
              <el-input v-model="form.discountRate" placeholder="请输入折扣率" type="number" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="最低消费金额" prop="minAmount">
              <el-input v-model="form.minAmount" placeholder="请输入最低消费金额" type="number" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 第三行：最高优惠金额、过期时间、来源渠道 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="最高优惠金额" prop="maxAmount">
              <el-input v-model="form.maxAmount" placeholder="请输入最高优惠金额" type="number" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="过期时间" prop="expireTime">
              <el-date-picker clearable
                v-model="form.expireTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择过期时间"
                style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="来源渠道" prop="source">
              <el-input v-model="form.source" placeholder="请输入来源渠道" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 第四行：备注（占满整行） -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listConponList, getConponList, delConponList, addConponList, updateConponList } from "@/api/fun/conponList"
import { listEcCoupon, getEcCoupon } from "@/api/fun/ecCoupon"
import { listUser, getUser } from "@/api/system/user"
import IdSelector from '@/components/IdSelector'
import { getDept } from "@/api/system/dept"

export default {
  name: "ConponList",
  dicts: ['ec_coupon_get_type', 'ec_coupon_user_status', 'ec_coupon_type'],
  components: {
    IdSelector
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 优惠券列表表格数据
      conponListList: [],
      // 当前用户的组织ID和部门ID
      currentOrgId: null,
      currentDeptId: null,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        couponCode: null,
        couponName: null,
        couponType: null,
        expireTime: null,
      },
      // 表单参数
      form: {},
      // API方法
      listEcCoupon,
      getEcCoupon,
      listUser,
      getUser,
      // 表单校验
      rules: {
        couponCode: [
          { required: true, message: "优惠券码不能为空", trigger: "blur" }
        ],
        couponName: [
          { required: true, message: "优惠券名称不能为空", trigger: "blur" }
        ],
        couponType: [
          { required: true, message: "优惠券类型不能为空", trigger: "change" }
        ],
        expireTime: [
          { required: true, message: "过期时间不能为空", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getCurrentUserInfo()
  },
  methods: {
    /** 查询优惠券列表列表 */
    getList() {
      this.loading = true
      listConponList(this.queryParams).then(response => {
        this.conponListList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        orgId: null,
        couponCode: null,
        couponName: null,
        couponType: null,
        couponAmount: null,
        discountRate: null,
        minAmount: null,
        maxAmount: null,
        expireTime: null,
        source: null,
        remark: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.couponId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加优惠券列表"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const couponId = row ? row.couponId : this.ids[0]
      if (!couponId) {
        this.$modal.msgError("请选择要修改的数据")
        return
      }
      getConponList(couponId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改优惠券列表"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 为删除的必填字段设置默认值
          const formData = { ...this.form }
          
          // 设置默认值
          if (!formData.createUserId) {
            formData.createUserId = this.$store.state.user.userInfo?.userId || 1
          }
          if (!formData.useStatus) {
            formData.useStatus = "0" // 默认未使用
          }
          if (!formData.getType) {
            formData.getType = "1" // 默认获取方式
          }
          if (!formData.getTime) {
            formData.getTime = new Date().toISOString().split('T')[0] // 当前日期
          }
          // orgId由后端Controller统一设置，前端不需要处理
          
          if (formData.couponId) {
        updateConponList(formData).then(response => {
          this.$modal.msgSuccess("修改成功")
          this.open = false
          this.getList()
        })
      } else {
        addConponList(formData).then(response => {
          this.$modal.msgSuccess("新增成功")
          this.open = false
          this.getList()
        })
      }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const couponIds = row ? [row.couponId] : this.ids
      if (!couponIds || couponIds.length === 0) {
        this.$modal.msgError("请选择要删除的数据")
        return
      }
      this.$modal.confirm('是否确认删除优惠券列表编号为"' + couponIds + '"的数据项？').then(function() {
        return delConponList(couponIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('fun/conponList/export', {
        ...this.queryParams
      }, `conponList_${new Date().getTime()}.xlsx`)
    },
    /** 获取当前用户信息 */
    getCurrentUserInfo() {
      // 从用户信息中获取组织ID和部门ID
      const userInfo = this.$store.state.user.userInfo
      if (userInfo) {
        this.currentOrgId = userInfo.orgId
        this.currentDeptId = userInfo.deptId
      }
    }
  }
}
</script>
